// 使用定时器进行定时循环处理某事件

#include <stdio.h>
#include "esp_log.h"
#include "driver/gpio.h"
#include "esp_event.h"
#include "driver/gptimer.h"



#define gpio_2 GPIO_NUM_2

// 开启
void gpio_up(gpio_num_t gpio_num)
{
    gpio_set_level(gpio_num,1);
};
// 关闭
void gpio_down(gpio_num_t gpio_num)
{
    gpio_set_level(gpio_num,0);
};

// GPIO 初始化配置
void gpio_init()
{
    gpio_config_t gpio_cfg = {
        .mode = GPIO_MODE_OUTPUT,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pin_bit_mask = 1ULL << 2,
    };

    gpio_config(&gpio_cfg);

    gpio_up(gpio_2);
}

// 定时器回调函数
bool test_alarm_cbt(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
    gpio_set_level(gpio_2,!gpio_get_level(gpio_2));
    return true;
};

// 定时器
void timer_init()
{   
    // 定时器配置
    gptimer_config_t gptimer_cfg = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 100000,
    };

    gptimer_handle_t gptimer_handle = {0};

    gptimer_new_timer(&gptimer_cfg, &gptimer_handle);

    // 定时器定时规则配置
    gptimer_alarm_config_t gptimer_alarm_cfg = {
        .alarm_count = 100000,
        .reload_count = 0,
        .flags.auto_reload_on_alarm = true,
    };

    gptimer_set_alarm_action(gptimer_handle, &gptimer_alarm_cfg);

    gptimer_event_callbacks_t cbs = {
        .on_alarm = test_alarm_cbt,
    };
    // 注册回调函数
    gptimer_register_event_callbacks(gptimer_handle, &cbs, NULL);
    gptimer_enable(gptimer_handle);
    gptimer_start(gptimer_handle);

}



void app_main(void)
{   
    gpio_init();
    timer_init();
    
    while (1)
    {   
        vTaskDelay(pdMS_TO_TICKS(500));
    }
}


